package com.jeecg.p3.system.poster.web;

import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.base.util.StringUtils;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StuAdvGroupService;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.poster.entity.PosterManager;
import com.jeecg.p3.system.poster.entity.ScanCodeNum;
import com.jeecg.p3.system.poster.entity.WhitePerson;
import com.jeecg.p3.system.poster.service.PosterManagerService;
import com.jeecg.p3.system.poster.service.ScanCodeNumService;
import com.jeecg.p3.system.poster.service.WhitePersonService;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/system/back/poster/posterMa")
public class PosterManagerController extends BaseController {
    @Autowired
    private PosterManagerService service;
    @Autowired
    private StudyAdvService studyAdvService;
    @Autowired
    private WhitePersonService whitePersonService;
    @Autowired
    private ScanCodeNumService scanCodeNumService;

    /**
     *
     * @param query 海报扫码统计查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/list",method = {RequestMethod.GET,RequestMethod.POST})
    public void toIndividual(@ModelAttribute PosterManager query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<PosterManager> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        pageQuery.setQuery(query);
        velocityContext.put("posManager",query);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        String viewName = "system/back/poster/posterManager_list.vm";
        if(isMobile(request)) {
            viewName = "system/back/app/my_scan_code_list.html";
        }
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    @RequestMapping(value="/findList",method = {RequestMethod.GET,RequestMethod.POST})
    public void findList(@ModelAttribute PosterManager query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<PosterManager> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        pageQuery.setQuery(query);
        velocityContext.put("posManager",query);
        List<StudyAdviser> advisers = studyAdvService.findByParam(new StudyAdviser());
        velocityContext.put("advisers", advisers);//传前台顾问信息

        /********************不统计人openid********************/
        List<StudyAdviser> stuList = studyAdvService.findByParam(null);
        List<WhitePerson> whitePersonList = whitePersonService.findByParam(null);
        String noOpenIds = "";
        for(StudyAdviser stu: stuList) {
            if(stu != null && StringUtils.isNotEmpty(stu.getOpenId())) {
                if(StringUtils.isEmpty(noOpenIds)) {
                    noOpenIds = "'" + stu.getOpenId() + "'";
                } else {
                    noOpenIds = noOpenIds + ",'" + stu.getOpenId() + "'";
                }
            }
        }
        for(WhitePerson white: whitePersonList) {
            if(white != null && StringUtils.isNotEmpty(white.getOpenId())) {
                if(StringUtils.isEmpty(noOpenIds)) {
                    noOpenIds = "'" + white.getOpenId() + "'";
                } else {
                    noOpenIds = noOpenIds + ",'" + white.getOpenId() + "'";
                }
            }
        }

        pageQuery.getQuery().setNoOpenIds(noOpenIds);
        List<Map<String, Object>> sumList = service.findGroupByParam(pageQuery);
        velocityContext.put("sumList", sumList);
        if(StringUtils.isNotEmpty(query.getStudyAdvGroup())) {
            velocityContext.put("studyGroup", true);
            Integer sumCount = 0;
            if(sumList != null) {
                for(Map<String, Object> m: sumList) {
                    Object count = m.get("counts");
                    if(count != null) {
                        sumCount = sumCount + Integer.valueOf(count.toString());
                    }

                }
            }
            velocityContext.put("sumCount", sumCount);
        }
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        String viewName = "system/back/poster/posterMa_list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    @RequestMapping(value="/toMyList",method = {RequestMethod.GET,RequestMethod.POST})
    public void toMyList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/app/my_scan_code_list.html";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    @ResponseBody
    @RequestMapping(value="/myList",method = {RequestMethod.GET,RequestMethod.POST})
    public Map<String, Object> myList(@ModelAttribute PosterManager query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        if(ComCode.day.equals(query.getQueryType()) && StringUtils.isNotEmpty(query.getStartDateTime())) {
            query.setStartDateTime(DateUtil.dateToString(new Date()) + " 00:00:00");
        } else if(ComCode.week.equals(query.getQueryType()) && StringUtils.isNotEmpty(query.getStartDateTime())) {
            query.setStartDateTime(DateUtil.getPastDate(7) + " 00:00:00");
        } else if(ComCode.month.equals(query.getQueryType()) && StringUtils.isNotEmpty(query.getStartDateTime())) {
            query.setStartDateTime(DateUtil.getPastDate(30) + " 00:00:00");
        }
        if(StringUtils.isNotEmpty(query.getStartDateTime())) {
            query.setStartDateTime(query.getStartDateTime());
        }
        if(StringUtils.isNotEmpty(query.getEndDateTime())) {
            query.setEndDateTime(query.getEndDateTime());
        }
        LoginUser user = getCurrentUser(request);
        Map<String, Object> map = new HashMap<>();
        if(!isAdmin(request)) {
            StudyAdviser adviser = studyAdvService.findByUserNumber(user.getUserId());
            query.setStuAdvId(adviser.getId());
        }
        PageQuery<PosterManager> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        pageQuery.setQuery(query);
        map.put("posManager", query);
        map.put("pageInfos", service.findPageList(pageQuery));
        return map;
    }

    /**
     * 日扫码统计
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/dayCount",method = {RequestMethod.GET,RequestMethod.POST})
    public void dayCount(HttpServletRequest request, HttpServletResponse response) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        List<StudyAdviser> stuList = studyAdvService.findByParam(null);
        List<WhitePerson> whitePersonList = whitePersonService.findByParam(null);
        String noOpenIds = "";
        /********************不统计人openid********************/
        for(StudyAdviser stu: stuList) {
            if(stu != null && StringUtils.isNotEmpty(stu.getOpenId())) {
                if(StringUtils.isEmpty(noOpenIds)) {
                    noOpenIds = "'" + stu.getOpenId() + "'";
                } else {
                    noOpenIds = noOpenIds + ",'" + stu.getOpenId() + "'";
                }
            }
        }
        for(WhitePerson white: whitePersonList) {
            if(white != null && StringUtils.isNotEmpty(white.getOpenId())) {
                if(StringUtils.isEmpty(noOpenIds)) {
                    noOpenIds = "'" + white.getOpenId() + "'";
                } else {
                    noOpenIds = noOpenIds + ",'" + white.getOpenId() + "'";
                }
            }
        }

        List<Map<String, Object>> pmList = service.findCount(noOpenIds);//统计数据
        velocityContext.put("pmList",pmList);
        String viewName = "system/back/poster/posterManager_day_list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/count",method = {RequestMethod.GET,RequestMethod.POST})
    public void count(HttpServletRequest request, HttpServletResponse response) throws Exception{
        VelocityContext velocityContext = new VelocityContext();

        List<Map<String, Object>> pmList = service.findCount("");//统计数据
        velocityContext.put("pmList",pmList);
        String viewName = "system/back/poster/posterManager_sum_list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 跳转到扫码图形展示界面
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/toScanCodeIcon",method = {RequestMethod.GET,RequestMethod.POST})
    public void toScanCodeIcon(HttpServletRequest request, HttpServletResponse response) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/poster/sacn_code_icon.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 获取图形展示数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/iconData",method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxJson iconData() {
        AjaxJson j = new AjaxJson();
        String lastMonth = DateUtil.getLastMonthInToday();//获取上个月
        String lastEndDate = DateUtil.dateToString(DateUtil.getLastDayInMonth(lastMonth));//上月最后一天
        String lastStartDate = DateUtil.dateToString(DateUtil.getFirstDayFromMonth(lastEndDate));//获取上月第一天
        String nowDate = DateUtil.dateToString(new Date());//当前日期
        String nowStartDate = DateUtil.dateToString(DateUtil.getFirstDayFromMonth(nowDate));//当月开始时间
        ScanCodeNum lastParam = new ScanCodeNum(lastStartDate, lastEndDate);//上月参数
        ScanCodeNum nowParam = new ScanCodeNum(nowStartDate, nowDate);//当月参数
        List<ScanCodeNum> lastList = scanCodeNumService.findByParam(lastParam);
        List<ScanCodeNum> nowList = scanCodeNumService.findByParam(nowParam);
        List<String> lastNum = new ArrayList<>();
        for(ScanCodeNum sc: lastList) {
            if(sc != null && StringUtils.isNotEmpty(sc.getNum())) {
                lastNum.add(sc.getNum());
            }
        }
        List<String> nowNum = new ArrayList<>();
        for(ScanCodeNum sc: nowList) {
            if(sc != null && StringUtils.isNotEmpty(sc.getNum())) {
                nowNum.add(sc.getNum());
            }
        }
        nowNum.add(service.findNowDayScanNum().toString());
        String[] lastArray = lastNum.toArray(new String[0]);
        String[] nowArray = nowNum.toArray(new String[0]);
        Map<String, Object> map = new HashMap<>();
        map.put("lastArray", lastArray);
        map.put("nowArray", nowArray);
        j.setObj(map);
        return j;
    }
}
